// miniprogram/pages/index/index.js
const { formatTime } = require('../../utils/util.js');
const { day } = require('../../utils/checkTimeout.js');
const { timeDifference2 } = require('../../utils/timeDifference.js');
const { sendCmd } = require('../../utils/sendCmds.js');
const { queryDownOrder } = require('../../utils/checkDown.js');
const db = wx.cloud.database();
const API_KEY = getApp().globalData.API_KEY;
const deviceId = getApp().globalData.deviceId;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    longitude:0,
    latitude:0,
    mapShow:false,
    markers:[
      { 
        id:1, latitude:34.822604321500634, longitude:113.53296328995512,
        callout:{
          content:'松园充电桩',bgColor:"#FF8C00",display:'ALWAYS',padding:5,color:'#FFFFFF'
        }, 
        iconPath:'/icons/charge.png' 
      },
      { 
        id:2, latitude:34.81257630538572, longitude:113.5325099966316, 
        callout:{
          content:'柳园充电桩',bgColor:"#FF8C00",display:'ALWAYS',padding:5,color:'#FFFFFF'
        }, 
        iconPath:'/icons/charge.png' 
      },
      { 
        id:3, latitude:34.81447013929131, longitude:113.53259046290205, 
        callout:{
          content:'荷园充电桩',bgColor:"#FF8C00",display:'ALWAYS',padding:5,color:'#FFFFFF'
        }, 
        iconPath:'/icons/charge.png' 
      },
      { 
        id:4, latitude:34.81761909232559, longitude:113.53583325360106, 
        callout:{
          content:'菊园充电桩',bgColor:"#FF8C00",display:'ALWAYS',padding:5,color:'#FFFFFF'
        }, 
        iconPath:'/icons/charge.png'
      }
    ],
    selectedMarker:{},
    sheetShow: false,
    actions: [
      { name: '详细信息' }
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.mapCtx = wx.createMapContext('myMap');
    // this.getMyLocation();
  },


   //移动到中心坐标
  focusLocation(){
    this.mapCtx.moveToLocation();
  },

  focusChargeLocation(){
    console.log(this.data.markers);
    let marker = {};
    this.data.markers.forEach(v=>{
      if (v.id === 1) {
        marker = v;
      }
    })
    this.mapCtx.moveToLocation({
      longitude:marker.longitude,
      latitude:marker.latitude
    });
  },

  getMyLocation(){
    let that = this;
    wx.showLoading({
      title: '正在获取当前位置',
      mask: true
    })
    wx.getLocation({
      type:'gcj02',
      success: (result) => {
        wx.hideLoading();
        let markers = that.data.markers;
        markers.push(
          { id:0, latitude:result.latitude, longitude:result.longitude, title:'我的位置', iconPath:'/icons/coordinate_main.png' }
        );
        that.setData({ 
          longitude:result.longitude,
          latitude:result.latitude,
          mapShow:true,
          markers
         })
      },
      fail: (res) => {
        wx.hideLoading();
        console.error(res);
      },
    })
  },
  
  
  clickMarker(e){
    const { markerId } = e.detail;
    if (markerId !== 1) {
      return;
    }
    const markers = this.data.markers;
    let selectedMarker = {};
    let latitude = 0;
    let longitude = 0;
    markers.forEach(v => {
      if (v.id === markerId) {
        longitude = v.longitude;
        latitude = v.latitude;
        selectedMarker = v;
        selectedMarker.deviceId = deviceId;
      }
    });
    this.mapCtx.moveToLocation({
      latitude:latitude,
      longitude:longitude
    });
    this.setData({ sheetShow:true,selectedMarker })
  },

  checkSetting(){
    const that = this;
    wx.getSetting({
      success:(res)=>{
        if (res.authSetting['scope.userLocation'] === false) {
          wx.authorize({
            scope: 'scope.userLocation',
            success: () => {
              that.getMyLocation();
            },
            fail:()=>{
              that.openConfirm();
            }
          })
        }
      }
    })
  },

  openConfirm(){
    wx.showModal({
      content: '检测到您没打开此小程序的定位权限，是否去设置打开？',
      confirmText: "确认",
      cancelText: "取消",
      success: function (res) {
        console.log(res);
        //点击“确认”时打开设置页面
        if (res.confirm) {
          console.log('用户点击确认')
          wx.openSetting({
            success: (res) => { }
          })
        } else {
          console.log('用户点击取消')
        }
      }
    });
  },

  onSheetClose() {
    this.setData({ sheetShow: false });
  },

  onSheetSelect(){
    const selectedMarker = this.data.selectedMarker;
    wx.navigateTo({
      url: `/pages/chargeDetail/index?markerId=${selectedMarker.id}`,
      success: (res) => {
        res.eventChannel.emit('getSelectedMarker', { data: selectedMarker });
      }
    })
  },


  //扫码
  onScanCode(){
    const userInfo = wx.getStorageSync('userInfo') || '';
    if (userInfo === '') {
      wx.showModal({
        confirmText: '知道了',
        content: '您还没有登录，请登录后再查看。',
        title: '请登录',
        showCancel:false,
      })
      return;
    }else if(userInfo && userInfo !== ''){
      //调用扫码接口
      wx.scanCode({
        onlyFromCamera: true,
        scanType: ['barCode','qrCode'],
        success: (result) => {
          console.log('扫码调用成功',result);
          this.queryNow(result.result,userInfo);
        },
        fail: (res) => {
          console.log('扫码调用失败');
        }
      });
      
    }  
  },

  queryNow(deviceId,userInfo){
    const that = this;
    //查询当前时间段我对这台设备的预约信息。
    db.collection('orders').orderBy('timestemp','desc').where({
      orderType:'will',
      _openid:userInfo.openId,
      deviceId:deviceId
    }).get({
      success: (res) => {
        console.log('[数据库] [查询记录] 成功: ', res.data);
        let orders = res.data;
        let nowTime = formatTime(new Date(new Date().getTime()));
        let orderOne = {};
        if(orders.length > 1){
          orders.forEach(v => {
            //到达预约时间且未逾期
            if((timeDifference2(v.orderTime,nowTime)<15 && timeDifference2(v.orderTime,nowTime)>=0) && day(v.timestemp)==day((new Date()).valueOf())){
              orderOne =  v;
            }
          });
        }else if(orders.length == 1){
          if((timeDifference2(orders[0].orderTime,nowTime)<15 && timeDifference2(orders[0].orderTime,nowTime)>=0) && day(orders[0].timestemp)==day((new Date()).valueOf())){
              orderOne = orders[0];
          }
        }  
        console.log('orderone',orderOne);
        if (orderOne.hasOwnProperty('_id')) {
            //这个时间段有预约
            //支付并使用,同时修改订单状态 
          console.log('我现在可以使用');
          let _data = {SET:"START",TIME:orderOne.orderHours};
          sendCmd(deviceId,API_KEY,JSON.stringify(_data));
          let status = 'success';
          wx.navigateTo({
            url: `/pages/public/index?status=${status}`,
          })
          db.collection('orders').doc(orderOne._id).update({
            data: {
              orderType: 'going',
              timestemp:(new Date()).valueOf()
            },
            success: (result) => {
              console.error('[数据库] [更新记录] 成功：', result);
            },
            fail: (error) => {
              console.error('[数据库] [更新记录] 失败：', error)
            }
          });
        }else{
          //没有预约，不可使用
          let status = 'fail';
          wx.navigateTo({
            url: `/pages/public/index?status=${status}`,
          })
        }
      },
      fail: (err) => {
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(!this.data.mapShow){
      this.getMyLocation();
    }
    this.checkSetting();
    queryDownOrder();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})